package xkp.lesson2;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class Server {
    public static void main(String[] args) throws IOException {
        System.out.println("服务器启动....");
        //NIO
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.bind(new InetSocketAddress(8888));
        //设置为非阻塞模式
        serverSocketChannel.configureBlocking(false);
        //当配置为非阻塞的话，面临的问题为 此处通道不管有没有客户端连接，都不会阻塞，如何和得知有客户端连接?????
        //SocketChannel socketChannel = serverSocketChannel.accept();
       //如何精准的捕获到客户端到来
        //1、创建Selector
        Selector selector = Selector.open();
        //2、把serverSocketChannel注册到selector中，并且要标明该通道关心的事情,
        // 可以通过selector监听该通道的SelectionKey.OP_CONNECT的事件
        serverSocketChannel.register(selector,SelectionKey.OP_ACCEPT);
        while(true){
            //select()会阻塞,如果selector监听的通道中有事情发生，则向下运行
            selector.select();
            //获取发生的事情
            Iterator<SelectionKey> keyIterator = selector.selectedKeys().iterator();
            while(keyIterator.hasNext()) {
                SelectionKey key = keyIterator.next();
                if(key.isAcceptable()) {
                    //此处表示有客户端来
                    //获取客户端，处理
                    ServerSocketChannel serverSocketChannel1 = (ServerSocketChannel) key.channel();
                    SocketChannel channel = serverSocketChannel1.accept();
                    System.out.println(channel.getRemoteAddress()+"连接成功");
                } else if (key.isConnectable()) {
                    // a connection was established with a remote server.
                } else if (key.isReadable()) {
                    // a channel is ready for reading
                } else if (key.isWritable()) {
                    // a channel is ready for writing
                }
                //一个事情处理完后删除
                keyIterator.remove();
            }
        }
        //System.out.println("----------------------------------");
    }
}
